<template xmlns="http://www.w3.org/1999/html">
  <div class="container">
    <el-header style="width: 100%">
      <el-menu :default-active="activeIndex"
               mode="horizontal"
               router
               style="width: 100%"
               class="el-menu-item">
        <el-menu-item index="/index">首页</el-menu-item>
        <el-menu-item index="/login">退出系统</el-menu-item>
        <el-menu-item style="margin-left: 82%;font-family: 'Microsoft YaHei';">欢迎您，{{ username }}</el-menu-item>
      </el-menu>
    </el-header>
    <div class="background-div"></div>
    <div class="user-info centered-div">
      <div class="user-card">
        <el-card class="blood-donation-card" style="text-align: left" shadow="hover">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div class="blood-info">
            <div class="avatar-container">
              <div class="centered-avatar">
                <img class="avatar" :src="userInfo.img" alt="User Avatar">
              </div>
            </div>
            <p><strong>姓名：</strong> {{ userInfo.donors }}</p>
            <p><strong>性别：</strong> {{ userInfo.sex }}</p>
            <p><strong>电话：</strong> {{ userInfo.phone }}</p>
            <p><strong>邮箱：</strong> {{ userInfo.email }}</p>
            <p><strong>血型：</strong> {{ userInfo.bloodType }} 型</p>
            <p><strong>地址：</strong> {{ userInfo.address }}</p>
          </div>
        </el-card>
        <el-card class="blood-donation-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>献血提醒</span>
          </div>
          <div class="blood-info" style="margin-top: 70px">
            <p style="text-align: left;margin-left: 50px">下次可献血时间: {{ nextDonationDate }}</p>
            <p style="text-align: left;margin-left: 50px">可献血地点:</p>
            <p style="text-align: left;margin-top: 10px"></p>
            <p v-for="(volume, index) in donationsites.slice(0, 3)" :key="index"> {{ volume }}</p>
          </div>
          <div class="encouragement">
            <p>热血无声，关爱有声，献血温暖人心！</p>
            <p>定期献血，传递爱的力量，共建和谐社会。</p>
          </div>
        </el-card>
        <el-card class="blood-donation-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>成就</span>
          </div>
          <div class="blood-info" style="margin-top: 80px ">
            <div class="blood-donation-info">
              <p class="donation-count">献血次数: {{ numberOfBloodDonations }}</p>
              <p class="donation-volume">献血量: {{ bloodDonationVolume }}</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <div style="border-bottom: 1px solid;margin: 0 50px">
      献血记录
      <el-button size="medium" @click="handleExport" style="margin-left: 20px;margin-bottom: 5px" type="primary">导出个人献血记录</el-button>
    </div>
    <div class="blood-donation-list">
      <el-row>
        <el-col :span="8" v-for="(record, index) in bloodDonationRecords" :key="index">
          <el-card class="blood-donation-card-1" shadow="hover">
            <div slot="header" class="clearfix">
              <span>{{ record.donoTime }}</span>
            </div>
            <div class="record-item">
              <div style="text-align: left"><span class="label">献血地点:</span> {{ record.origin }}</div>
              <div style="text-align: left"><span class="label">献血量:</span> {{ record.donoNum }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import request from "@/utils/request";
import * as XLSX from "xlsx";
export default {
  name: 'UserInfoCard',
  data() {
    return {
      exportData: '',
      testData: [
        ['献血记录表'],
        ['献血者:李思思 性别:女 血型：AB'],
        ['献血时间', '献血者', '血型', '献血量', '来源', '性别'],
        {
          '献血时间': '2024-04-14 00:33:54',
          '献血者': '李思思',
          '血型': 'AB',
          '献血量': '200',
          '来源': '北京市通州区中心血站',
          '性别': '女'
        },
        {
          '献血时间': '2024-04-14 00:33:54',
          '献血者': '李思思',
          '血型': 'AB',
          '献血量': '200',
          '来源': '北京市通州区中心血站',
          '性别': '女'
        },
      ],
      username: '',
      actualname: '',
      donationsites: [],
      numberOfBloodDonations: '',
      bloodDonationVolume: '',
      bloodDonationRecords: [
        {
          date: '2024-04-10',
          location: 'XX医院',
          amount: '400ml'
        },
        {
          date: '2024-03-25',
          location: 'XX社区卫生站',
          amount: '300ml'
        },
      ],
      nextDonationDate: '2024-05-01', // 下次可献血时间
      donationLocation: 'XX献血站', // 可献血地点
      userInfo: {
        name: '',
        sex: '',
        phone: '',
        email: '',
        address: '',
        type: ''
      },
      activeIndex: 'home'
    };

  },
  methods: {
    handleExport() {
      if (this.exportData.length) {
        const tempData = this.exportData;
        const newInfo = {
          donors: '献血者：' + this.exportData[0].donors + ' 性别：' + this.exportData[0].sex + ' 血型：' + this.exportData[0].bloodType,
        };
        tempData.push(newInfo)
        console.log(newInfo);
        const data = tempData.map(item => {
          return {
            '献血者': item.donors,
            '献血时间': item.donoTime,
            '血型': item.bloodType,
            '献血量': item.donoNum,
            '来源': item.origin,
            '性别': item.sex,
          }
        });
        const sheet = XLSX.utils.json_to_sheet(data);
        sheet['!merges'] = [
          {s: {r: tempData.length, c: 0}, e: {r: tempData.length, c: 6}}, // 合并单元格
        ]
        const cellRange = XLSX.utils.decode_range("A1:G10"); // 范围从A1到C3
        sheet['!rows'] = [];
        for (let R = cellRange.s.r; R <= cellRange.e.r; ++R) {
          sheet['!rows'].push({ height: 20 }); // 设置所有行的高度
        }
        // 设置第一行的样式
        sheet[XLSX.utils.encode_cell({ r: 0, c: 0 })].s = { // A1单元格
          fill: { patternType: "solid", fgColor: { rgb: "FFFF0000" } }, // 背景色红色
          font: { color: { rgb: "FFFFFF" } }, // 字体颜色白色
          alignment: { horizontal: "center", vertical: "center" } // 水平垂直居中
        };
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, sheet, '献血记录');
        XLSX.writeFile(workbook,  JSON.parse(localStorage.getItem('name')).actualname +' 献血记录表.xlsx');
        tempData.pop()
      } else {
        this.$message({
          type: "info",
          message: '无记录导出'
        })
      }
    },
    getBloodDonationData() {
      request.get('/history/export/' + JSON.parse(localStorage.getItem('name')).actualname).then(res => {
        if (res.code === '200') {
          console.log(res);
          this.exportData = res.data;
          this.userInfo = res.data;
          this.userInfo.sex = res.data[0].sex
          this.userInfo.bloodType = res.data[0].bloodType
          const tempInfo = JSON.parse(localStorage.getItem("name"));
          this.userInfo.donors = tempInfo.actualname
          this.userInfo.address = tempInfo.address
          this.userInfo.phone = tempInfo.phone
          this.userInfo.img = tempInfo.image
          this.userInfo.email = tempInfo.email
          console.log(this.userInfo);
          this.bloodDonationRecords = res.data
          this.numberOfBloodDonations = this.bloodDonationRecords.length;
          this.bloodDonationVolume = this.bloodDonationRecords.reduce((total, record) => {
            // 使用 parseInt 或 parseFloat 将字符串转换为数值型
            const num = parseInt(record.donoNum); // 或者使用 parseFloat(record.donoNum) 如果是浮点数
            // 检查 num 是否为有效数值，如果是则累加到 total 中
            if (!isNaN(num)) {
              return total + num;
            } else {
              return total; // 如果不是有效数值，则保持原值不变
            }
          }, 0);
          const lastDonoTime = this.bloodDonationRecords.reduce((lastDate, record) => {
            // 解析日期字符串
            const currentDate = new Date(record.donoTime);

            // 如果 currentDate 大于 lastDate，则更新为当前日期
            if (currentDate > lastDate) {
              return currentDate;
            } else {
              return lastDate;
            }
          }, new Date(0)); // 初始值为最小日期
          const delayedDate = new Date(lastDonoTime);
          delayedDate.setDate(lastDonoTime.getDate() + 12 * 7); // 推迟十二天后的日期
          console.log(delayedDate);
          this.nextDonationDate = delayedDate.toISOString().slice(0, 10)
        } else {
          this.$message({
            type: "info",
            message: res.msg
          })
        }
      })
    },
    getBloodDonationLocation() {
      request.get('/sites/allsites').then(res => {
        this.donationsites = res.data;
      })
    },
    // getName() {
    //   this.actualname = JSON.parse(localStorage.getItem('name')).actualname;
    // },
    getInfo() {
      request.get('/donorinfo/getOne/' + JSON.parse(localStorage.getItem('name')).actualname).then(res => {
        if (res.code === '200') {

        } else {
          this.$message({
            type: "info",
            message: res.msg
          })
        }
      })
    },
    loadPerson() {
      this.username = JSON.parse(localStorage.getItem('name')).actualname
      this.address = JSON.parse(localStorage.getItem('name')).address
      this.phone = JSON.parse(localStorage.getItem('name')).phone
      this.email = JSON.parse(localStorage.getItem('name')).email
      this.usertype = JSON.parse(localStorage.getItem('name')).userType
    },
  },
  mounted() {
    this.getInfo()
    this.getBloodDonationData()
    this.getBloodDonationLocation()
    // 在组件挂载到 DOM 上后执行的逻辑
    // 执行其他 DOM 操作
  },
  created() {
    this.loadPerson()
  }
};
</script>

<style scoped>

.container {
  text-align: center; /* 水平居中容器内的块级元素 */
}

.background-div {
  width: 100%;
  height: 300px;
  background-image: url('xxx.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center; /* 设置背景图片的位置居中 */
  background-color: #fa9f9c;
}

.centered-div {
  display: inline-block; /* 让元素变成块级元素，以便设置水平居中 */
  margin: 0 auto; /* 左右居中 */
  /* 这里可以添加你需要的样式 */
}

.user-info {
  width: 100%;
}

.user-card {
  display: flex;
  justify-content: space-evenly;
  margin-bottom: 20px;
}

.avatar-container {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.blood-donation-card {
  width: 450px; /* 卡片宽度 */
  margin: 25px; /* 卡片间距 */
}


.blood-info {
  margin-bottom: 20px;
}

.encouragement {
  color: #666;
}

.blood-donation-list {
  padding: 20px;
}

.blood-donation-card-1 {
  margin: 20px;
}

.record-item {
  margin-top: 10px;
}

.label {
  font-weight: bold;
  margin-right: 5px;
}

.avatar-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 100px; /* 调整容器高度 */
}

.centered-avatar {
  /* 可以添加一些样式，比如最大宽度或者最大高度 */
}

.blood-donation-info p {
  font-size: 24px; /* 设置字体大小 */
  font-weight: bold; /* 设置字体粗细 */
  color: #d94e4e; /* 设置字体颜色，选择一种艺术感较强的颜色 */
  text-shadow: 1px 1px 2px #000; /* 添加文字阴影，增加立体感 */
  font-family: 'Arial', sans-serif; /* 设置字体类型 */
  text-align: center; /* 文本居中显示 */
  margin-bottom: 10px; /* 设置段落间距 */
}

.donation-volume {
  margin: 50px;
  letter-spacing: 0.5px; /* 增加字母间距，增加可读性 */
}

.el-menu-item.is-active {
  background-color: #ffffff !important;
  color: #000000 !important;
}

</style>